import cv2
import numpy as np
import matplotlib.pyplot as plt
def add_gaussian_noise(img,mean=0,sigma=25):
 gauss = np.random.normal(mean, sigma, img.shape)
# 根据均值和标准差生成符合高斯分布的噪声
 image_gaussian = img + gauss
# 给图片添加高斯噪声
 image_gaussian = np.clip(image_gaussian, a_min=0, a_max=255)
# 设置图片添加高斯噪声之后的像素值的范围
 return image_gaussian
def add_sp_noise(img,s_vs_p = 0.5,amount = 0.04):
 # s_vs_p 设置添加椒盐噪声的数目比例
 # amount 设置添加噪声图像像素的数目
 image_sp = np.copy(img)
 # 添加 salt 噪声
 num_salt = np.ceil(amount * img.size * s_vs_p)
 coords = [np.random.randint(0, i - 1, int(num_salt)) for i in img.shape]
# 设置添加噪声的坐标位置
 image_sp[tuple(coords)] = 255
 # 添加 pepper 噪声
 num_pepper = np.ceil(amount * img.size * (1. - s_vs_p))
 coords = [np.random.randint(0, i - 1, int(num_pepper)) for i in img.shape]
# 设置添加噪声的坐标位置
 image_sp[tuple(coords)] = 0
 return image_sp
def main():
 grayimg = cv2.imread('camera.png', cv2.IMREAD_GRAYSCALE)
 print(np.max(grayimg))
 plt.figure(figsize=(8, 8)) # 显示原始图像
 plt.subplot(2, 4, 1), plt.imshow(grayimg, cmap='gray'), plt.title('original img')
 image_gaussian = add_gaussian_noise(grayimg) # 加高斯噪声
 plt.subplot(2, 4, 2), plt.imshow(image_gaussian, cmap='gray'), plt.title('Gaussian Noise Image')
 image_sp = add_sp_noise(grayimg) # 加椒盐噪声
 plt.subplot(2, 4, 3), plt.imshow(image_sp, cmap='gray'), plt.title('Salt Noise Image')
 # 对图像均值滤波，核大小为 3x3
 Mean_gaussian = cv2.blur(image_gaussian, ksize=(3, 3))
 Mean_sp = cv2.blur(image_sp, ksize=(3, 3))
# 对图像中值滤波，核大小为 3x3
 Median_gaussian = cv2.medianBlur(np.uint8(image_gaussian), 3)
 Median_sp = cv2.medianBlur(np.uint8(image_sp), 3)
 plt.subplot(2, 4, 5), plt.imshow(Mean_gaussian, cmap='gray'), plt.title('Mean Filtering For Gaussian Noise')
 plt.subplot(2, 4, 6), plt.imshow(Median_gaussian, cmap='gray'), plt.title('Median Filtering For Gaussian Noise')
 plt.subplot(2, 4, 7), plt.imshow(Mean_sp, cmap='gray'), plt.title('Mean Filtering For Salt Noise')
 plt.subplot(2, 4, 8), plt.imshow(Median_sp, cmap='gray'), plt.title('Median Filtering For Salt Noise')
 plt.show()
if __name__ == '__main__':
 main()